<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/struts-nested.tld" prefix="nested" %>
<%@ taglib uri="/WEB-INF/chiptrack-tags.tld" prefix="chiptrack" %>

<chiptrack:checkLogon sourcePage="/directMarginReport.do" />
<%String chipTracContext = "/" + ConfigManager.getChipTracContext();%>

<HTML>
<HEAD><TITLE>Scalarsoft - ChipTrac</TITLE>
<LINK href="<%=chipTracContext%>/jsp/includes/stylesheets/scalarsoft.css" type="text/css" rel="stylesheet">
<script src="<%=chipTracContext%>/jsp/includes/scripts/functions.js"></script>
<script src="<%=chipTracContext%>/jsp/includes/scripts/validations.js"></script>
<script src="<%=chipTracContext%>/jsp/includes/scripts/quickSearch.js"></script>
<script src="<%=chipTracContext%>/jsp/includes/scripts/ajax_utils.js"></script>
<SCRIPT language="JavaScript">
var newRowCount = 0;
function showDirectMarginDetailsByCustomer( customerId )
{
    var form = document.directMarginReportForm;

    form.customerId.value = customerId;
    form.action = "<%=chipTracContext%>/directMarginReport.do"
    form.submit();

}

function showDirectMarginDetailsByProduct( processstepId  )
{
    var form = document.directMarginReportForm;

    form.processstepId.value = processstepId;
    form.action = "<%=chipTracContext%>/directMarginReport.do"
    form.submit();

}

function showDirectMarginDetailsByCostCode( costCode )
{
    var form = document.directMarginReportForm;

    form.costCode.value = costCode;
    form.action = "<%=chipTracContext%>/directMarginReport.do"
    form.submit();

}
        
function showSalesOrderDetails( customerId, processstepId )
{
    var form = document.directMarginReportForm;

    form.customerId.value = customerId;
    form.processstepId.value = processstepId;
    form.action = "<%=chipTracContext%>/directMarginReport.do"
    form.submit();

}

function showSalesOrderDetailsCostCode( costCode, processstepId )
{
    var form = document.directMarginReportForm;

    form.costCode.value = costCode;
    form.processstepId.value = processstepId;
    form.action = "<%=chipTracContext%>/directMarginReport.do"
    form.submit();

}
function showBusy( isBusy )
{
   var requestStatusMsg = document.getElementById("errors");
   if ( isBusy )
    requestStatusMsg.innerHTML = "Processing..."
   else
    requestStatusMsg.innerHTML = ""
}
function removeChildsOf ( trId )
{
    var dmTable = document.getElementById("directMarginTable");
    var trCtrl = document.getElementById ( trId );
    var rowIndex = trCtrl.rowIndex;
    var parentName = trCtrl.name;
    var childName = "_" + parentName;
    var subChildName = "_" + childName;
    var isRemovedChilds = false;
    //alert ( "parentName=" + parentName + ":childName=" + childName + ":subChildName" + subChildName )
    while ( true )
    {
        var childTR = dmTable.rows(rowIndex+1);
        if ( childTR != null && (childTR.name==childName || childTR.name==subChildName) )
        {
            dmTable.deleteRow(rowIndex+1);
            isRemovedChilds = true;
        }
        else
        {
            break;
        }
    }
    return isRemovedChilds;
}
function showDirectMarginDetails(customerId, processStepId, costCode, groupBy, trId)
{
    showBusy(true);
    var form = document.directMarginReportForm;

    if ( removeChildsOf(trId) ) //table collapsed no need to expand
    {
        showBusy(false);
        return;
    }

    var params = "action=ajaxLoadDirectMargins";
    params += "&searchCostCode=" + (costCode == null ? form.searchCostCode.value : costCode);
    params += "&searchProcessstepId=" + (processStepId == null ? form.searchProcessstepId.value : processStepId);
    params += "&searchCustomerId=" + (customerId == null ? form.searchCustomerId.value : customerId);
    params += "&searchStatus=" + form.searchStatus.value;
    params += "&searchDMPercentage=" + form.searchDMPercentage.value;
    params += "&searchDMPercentageOptr=" + form.searchDMPercentageOptr.value;
    params += "&searchDateType=" + form.searchDateType.value;
    params += "&searchFromDate=" + form.searchFromDate.value;
    params += "&searchToDate=" + form.searchToDate.value;
    params += "&searchGroupBy=" + (groupBy == null ? form.searchGroupBy.value : groupBy);
    params += "&searchSortBy=" + form.searchSortBy.value;
    params += "&searchOrderBy=" + form.searchOrderBy.value;

    // Obtain an XMLHttpRequest instance
    req = newXMLHttpRequest();
    // Set the handler function to receive callback notifications
    // from the request object
    var handlerFunction;
    handlerFunction = getReadyStateHandler(req, directMarginXMLHandler, trId);
    req.onreadystatechange = handlerFunction;
    // Open an HTTP POST connection to the shopping cart servlet.
    // Third parameter specifies request is asynchronous.
    req.open("POST", "<%=chipTracContext%>/directMarginReport.do", true);
    // Specify that the body of the request contains form data
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    // Send form encoded data
    req.send(params);
}
function directMarginXMLHandler(directMarginXML, trId)
{
    if (req)
    {
        delete req;
    }

    /*
        <dms>
            <exception></exception>
            <grpby></grpby>
            <dm>
                <cust id=""></cust>
                <pn id=""></pn>
                <cc></cc>
                <so></so>
                <ac></ac>
                <units></units>
                <ucost></ucost>
                <amount></amount>
                <dmargin></dmargin>
                <dmpcent></dmpcent>
            </dm>
            <dm>
                ...
            </dm>
            ...
        </dms>
    */
    var form = document.directMarginReportForm;
    var baseGrpBy = form.searchGroupBy.value;

    var dmBody = document.getElementById("directMarginTable");
    var trCtrl = document.getElementById(trId);
    var insertRowIdex = trCtrl.rowIndex + 1;

    var exceptionNode = directMarginXML.getElementsByTagName("dms")[0].getElementsByTagName("exception")[0].firstChild;
    if ( exceptionNode != null )
    {
        var newRow = dmBody.insertRow(insertRowIdex);
        newRow.name = "_" + trCtrl.name;
        newRow.className = "NArialL";
        var cell = newRow.insertCell();
        cell.colSpan = "5";
        cell.innerHTML = "<font color='red'>" + exceptionNode.nodeValue + "</font>";
    }
    else
    {
        var dmGrpBy = directMarginXML.getElementsByTagName("dms")[0].getElementsByTagName("grpby")[0].firstChild.nodeValue;
        var dms = directMarginXML.getElementsByTagName("dms")[0].getElementsByTagName("dm");

        var onClickAchr = "";
        for (var k = 0; k < dms.length; k++)
        {
            var dm = dms[k];
            //alert ( dm.getElementsByTagName("cust")[0].getAttribute( "id" ) )

            var custId = dm.getElementsByTagName("cust")[0].getAttribute("id");
            var custName = dm.getElementsByTagName("cust")[0].firstChild.nodeValue;
            var psId = dm.getElementsByTagName("pn")[0].getAttribute("id");
            var partNumber = dm.getElementsByTagName("pn")[0].firstChild.nodeValue;
            var costCode = dm.getElementsByTagName("cc")[0].firstChild.nodeValue;
            var salesOrder = dm.getElementsByTagName("so")[0].firstChild.nodeValue;
            var actualCost = dm.getElementsByTagName("ac")[0].firstChild.nodeValue;
            var units = dm.getElementsByTagName("units")[0].firstChild.nodeValue;
            var unitCost = dm.getElementsByTagName("ucost")[0].firstChild.nodeValue;
            var amount = dm.getElementsByTagName("amount")[0].firstChild.nodeValue;
            var dmargin = dm.getElementsByTagName("dmargin")[0].firstChild.nodeValue;
            var dmpcent = dm.getElementsByTagName("dmpcent")[0].firstChild.nodeValue;
            var innerRowId = "";
            var col1 = "";
            var col2 = "";
            var col3 = "";
            var bgColor = "";
            if (baseGrpBy == "customer")
            {
                if (dmGrpBy == "product")
                {
                    col1 = "";
                    col2 = partNumber;
                    col3 = "";
                    innerRowId = trCtrl.name + "_" + psId;
                    bgColor = "#D0D0D0";
                    onClickAchr = "<A onclick='javascript:showDirectMarginDetails(" + custId + "," + psId + ",null,\"salesOrder\",\"" + innerRowId + "\");' style='cursor:hand;'>";
                }
                if (dmGrpBy == "salesOrder")
                {
                    col1 = "";
                    col2 = "";
                    col3 = salesOrder;
                    bgColor = "#E0E0E0";
                    innerRowId = "";
                    onClickAchr = "";
                }
            }
            else if (baseGrpBy == "product")
            {
                if (dmGrpBy == "customer")
                {
                    col1 = "";
                    col2 = custName;
                    col3 = "";
                    innerRowId = trCtrl.name + "_" + custId;
                    bgColor = "#D0D0D0";
                    onClickAchr = "<A onclick='javascript:showDirectMarginDetails(" + custId + "," + psId + ",null,\"salesOrder\",\"" + innerRowId + "\");' style='cursor:hand;'>";
                }
                if (dmGrpBy == "salesOrder")
                {
                    col1 = "";
                    col2 = "";
                    col3 = salesOrder;
                    bgColor = "#E0E0E0";
                    innerRowId = "";
                    onClickAchr = "";
                }
            }
            else if (baseGrpBy == "costCode")
            {
                if (dmGrpBy == "product")
                {
                    col1 = "";
                    col2 = partNumber;
                    col3 = "";
                    innerRowId = trCtrl.name + "_" + psId;
                    bgColor = "#D0D0D0";
                    onClickAchr = "<A onclick='javascript:showDirectMarginDetails( null," + psId + ",\"" + costCode + "\",\"customer\",\"" + innerRowId + "\");' style='cursor:hand;'>";
                }
                if (dmGrpBy == "customer")
                {
                    col1 = "";
                    col2 = "";
                    col3 = custName;
                    bgColor = "#E0E0E0";
                    innerRowId = "";
                    onClickAchr = "";
                }
            }

            var newRow = dmBody.insertRow(insertRowIdex+k);
            newRow.name = "_" + trCtrl.name;
            if (innerRowId != "")
                newRow.id = innerRowId;
            newRow.className = "NArialL";
            newRow.bgColor = bgColor;
            /* if (onClick != "")
            {
                //alert ( eval("javascript:showDirectMarginDetails(" + custId + ", " + psId + ",null,'salesOrder','" + innerTbodyId + "','sujan_" + newRowCount + "')" ) );
                var temp = "showDirectMarginDetails("+ custId + "," + new String(psId) + ",null,\"salesOrder\",\"" + innerTbodyId + "\",\""+newRow.id+"\");";
                alert ( "temp:" + temp )
                newRow.attachEvent("onmousedown", function (custId, psId)
                                                    {
                                                        alert ( "psId:" + psId )
                                                        var pid = new String(psId);
                                                        //alert ( "infun:" + temp )
                                                        showDirectMarginDetails( eval(custId), pid,null,"salesOrder", '"' + innerTbodyId + "'", "'" + "sujan_"+newRowCount + "'");
                                                    });//function () { alert('sujan') });
            }*/
            var cell = newRow.insertCell();
            cell.innerHTML = onClickAchr + col1 + ( onClickAchr!="" ? "</A>" : "" );
            cell = newRow.insertCell();
            cell.innerHTML = onClickAchr + col2 + ( onClickAchr!="" ? "</A>" : "" );
            cell = newRow.insertCell();
            cell.innerHTML = onClickAchr + col3 + ( onClickAchr!="" ? "</A>" : "" );
            cell = newRow.insertCell();
            cell.align = "right";
            cell.innerHTML = onClickAchr + amount + ( onClickAchr!="" ? "</A>" : "" );
            cell = newRow.insertCell();
            cell.align = "right";
            cell.innerHTML = onClickAchr + dmpcent + ( onClickAchr!="" ? "</A>" : "" );            
            cell = newRow.insertCell();
            cell.align = "right";
            cell.innerHTML = onClickAchr + units + ( onClickAchr!="" ? "</A>" : "" );
            cell = newRow.insertCell();
            cell.align = "right";
            cell.innerHTML = onClickAchr + unitCost + ( onClickAchr!="" ? "</A>" : "" );
            cell = newRow.insertCell();
            cell.align = "right";
            cell.innerHTML = onClickAchr + actualCost + ( onClickAchr!="" ? "</A>" : "" );
            cell = newRow.insertCell();
            cell.align = "right";
            cell.innerHTML = onClickAchr + dmargin + ( onClickAchr!="" ? "</A>" : "" );

        }
    }
    showBusy(false);
}
function exportToFile()
{
    var form = document.directMarginReportForm;
    var url = "<%=chipTracContext%>/directMarginReport.do?action=exportDirectMargins"
    url += "&searchCostCode=" + form.searchCostCode.value;
    url += "&searchProcessstepId=" + form.searchProcessstepId.value;
    url += "&searchCustomerId=" + form.searchCustomerId.value;
    url += "&searchStatus=" + form.searchStatus.value;
    url += "&searchDMPercentage=" + form.searchDMPercentage.value;
    url += "&searchDMPercentageOptr=" + form.searchDMPercentageOptr.value;
    url += "&searchDateType=" + form.searchDateType.value;
    url += "&searchFromDate=" + form.searchFromDate.value;
    url += "&searchToDate=" + form.searchToDate.value;
    url += "&searchGroupBy=" + form.searchGroupBy.value;
    url += "&searchSortBy=" + form.searchSortBy.value;
    url += "&searchOrderBy=" + form.searchOrderBy.value;
    newWindow = window.open ( url, 'directMarginReport', 'channelmode=no,directories=no,toolbar=no,menubar=no,personalbar=no,status=no,scrollbars=yes,width=450,height=150,resizable=yes');
}
</SCRIPT>
</HEAD>
<BODY bgColor="#ffffff" leftMargin="0" topMargin="0" marginheight="0" marginwidth="0">
<!-- Top Header Start-->
<%@ include file="/jsp/includes/header.jsp" %>
<!-- Top Header End-->
<TABLE cellSpacing=0 cellPadding=0 width="100%" border=0>
<TBODY>
    <TR>
	    <TD width='180' valign='top' background='<%=chipTracContext%>/jsp/includes/images/left_red_bg.gif'>
            <!-- Side Navigation start -->
            <%@include file="/jsp/finance/finance_reports_menu.jsp" %>
            <!-- end of the side navigations -->
        </TD>
	    <TD bgcolor="#ffffff"><IMG height=9 src="<%=chipTracContext%>/jsp/includes/images/spacer.gif" width=8></TD>
	    <TD bgcolor="#ffffff"><IMG height=480 src="<%=chipTracContext%>/jsp/includes/images/spacer.gif" width=2></TD>
	    <TD valign="top" width="100%"><IMG height=1 src="<%=chipTracContext%>/jsp/includes/images/clear.gif" width=500 border=0>
            <BR>
            <html:form action="/directMarginReport.do" name="directMarginReportForm" type="com.scalar.chiptrack.finance.reports.forms.DirectMarginReportForm">
            <TABLE width="95%" align="right" cellpadding="2" cellspacing="2" border="0" >
                <TR>
                    <TD colspan="8" class="NArialW" align="center">
                        Direct Margin Report
                        <nested:hidden property="searchCostCode"/>
                        <nested:hidden property="searchProcessstepId"/>
                        <nested:hidden property="searchCustomerId"/>
                        <nested:hidden property="searchStatus"/>
                        <nested:hidden property="searchDMPercentage"/>
                        <nested:hidden property="searchDMPercentageOptr"/>
                        <nested:hidden property="searchDateType" />
                        <nested:hidden property="searchFromDate" />
                        <nested:hidden property="searchToDate" />
                        <nested:hidden property="searchGroupBy" />
                        <nested:hidden property="searchSortBy" />
                        <nested:hidden property="searchOrderBy" />
                    </TD>
                </TR>
                <TR><TD colspan='8' CLASS="NArialL"><CENTER><A HREF="javascript:exportToFile()">[Export To File]</A></CENTER></TD></TR>
                <TR><TD colspan='8' align="left" class='NArialL'>&nbsp;<FONT id="errors" color='FF0000'></font></TD></TR>
                <TR><TD colspan='8' class="NArialL"><chiptrack:errors styleClass="NArialL"/><chiptrack:info styleClass="NArialL"/></TD></TR>

                <TR>
                    <TD colspan='8'>
                        <TABLE width="100%" align="center" cellpadding="1" cellspacing="1" border="0" id="directMarginTable">
                        <tr>
                            <td width="20%" align="center" bgcolor="#993333" class="NArialL">
                                <font color="#FFFFFF">
                                <logic:equal name="directMarginReportForm" value="customer" property="searchGroupBy">
                                    Customer
                                </logic:equal>
                                <logic:equal name="directMarginReportForm" value="product" property="searchGroupBy">
                                    Product
                                </logic:equal>
                                <logic:equal name="directMarginReportForm" value="costCode" property="searchGroupBy">
                                    Cost Code
                                </logic:equal>
                                </font>
                            </td>
                            <td width="15%" align="center" bgcolor="#993333" class="NArialL">
                                <font color="#FFFFFF">
                                <logic:equal name="directMarginReportForm" value="customer" property="searchGroupBy">
                                    Product
                                </logic:equal>
                                <logic:equal name="directMarginReportForm" value="product" property="searchGroupBy">
                                    Customer
                                </logic:equal>
                                <logic:equal name="directMarginReportForm" value="costCode" property="searchGroupBy">
                                    Product
                                </logic:equal>
                                </font>
                            </td>
                            <td width="12%" align="center" bgcolor="#993333" class="NArialL">
                                <font color="#FFFFFF">
                                <logic:equal name="directMarginReportForm" value="customer" property="searchGroupBy">
                                    Sales Order
                                </logic:equal>
                                <logic:equal name="directMarginReportForm" value="product" property="searchGroupBy">
                                    Sales Order
                                </logic:equal>
                                <logic:equal name="directMarginReportForm" value="costCode" property="searchGroupBy">
                                    Customer
                                </logic:equal>
                                </font>
                            </td>
                            <td width="8%" align="center" bgcolor="#993333" class="NArialL"><font color="#FFFFFF">Revenue</font></td>
                            <td width="11%" align="center" bgcolor="#993333" class="NArialL"><font color="#FFFFFF">Direct Margin %</font></td>                            
                            <td width="8%" align="center" bgcolor="#993333" class="NArialL"><font color="#FFFFFF">Units</font></td>
                            <td width="8%" align="center" bgcolor="#993333" class="NArialL"><font color="#FFFFFF">ASP</font></td>
                            <td width="8%" align="center" bgcolor="#993333" class="NArialL"><font color="#FFFFFF">Std Cost</font></td>
                            <td width="8%" align="center" bgcolor="#993333" class="NArialL"><font color="#FFFFFF">Direct Margin/Unit</font></td>
                        </tr>
                        <nested:iterate property="directMarginList" indexId="idx" id="listItemLevelOne" type="com.scalar.chiptrack.finance.reports.DirectMargin">
                            <% String onclickLevelOne = ""; String rowId = ""; %>
                            <logic:equal name="directMarginReportForm" value="customer" property="searchGroupBy">
                                <%
                                    rowId = "DM" + listItemLevelOne.getCustomerId();
                                    onclickLevelOne = "javascript:showDirectMarginDetails(" + listItemLevelOne.getCustomerId() + ",null,null,'product','"+rowId+"');";
                                %>
                            </logic:equal>
                            <logic:equal name="directMarginReportForm" value="product" property="searchGroupBy">
                                <%
                                    rowId = "DM" + listItemLevelOne.getProcessstepId();
                                    onclickLevelOne = "javascript:showDirectMarginDetails(null," + listItemLevelOne.getProcessstepId() + ",null,'customer','"+rowId+"');";
                                %>
                            </logic:equal>
                            <logic:equal name="directMarginReportForm" value="costCode" property="searchGroupBy">
                                <%
                                    rowId = "DM" + listItemLevelOne.getCostCode();
                                    onclickLevelOne = "javascript:showDirectMarginDetails(null,null,'" + listItemLevelOne.getCostCode() + "','product','"+rowId+"');";
                                %>
                            </logic:equal>
                            <tr bgcolor="#CDCEE9" CLASS="NArialL" onclick="<%=onclickLevelOne%>" name="<%=rowId%>" id="<%=rowId%>" style="cursor:hand;">
                                <td align="left" class="NArialL">
                                    <img src="<%=chipTracContext%>/jsp/includes/images/bullet2.GIF" width="12" height="12">&nbsp;
                                    <logic:equal name="directMarginReportForm" value="customer" property="searchGroupBy">
                                        <nested:write property="customerName"/>
                                    </logic:equal>
                                    <logic:equal name="directMarginReportForm" value="product" property="searchGroupBy">
                                        <nested:write property="partNumber"/>
                                    </logic:equal>
                                    <logic:equal name="directMarginReportForm" value="costCode" property="searchGroupBy">
                                        <nested:write property="costCode"/>
                                    </logic:equal>
                                </td>
                                <td align="left" class="NArialL">
                                    &nbsp;
                                </td>
                                <td align="left" class="NArialL">
                                    <%--<nested:write property="salesOrderNo" />--%>
                                </td>
                                <td align="right" class="NArialL"><nested:write property="unitsPriceFormatted" /></td>
                                <td align="right" class="NArialL"><nested:write property="directMarginPerctageFormatted" /></td>
                                <td align="right" class="NArialL"><nested:write property="unitsFormatted" /></td>
                                <td align="right" class="NArialL"><nested:write property="unitsCostFormatted" /></td>
                                <td align="left" class="NArialL">
                                    <%--<nested:write property="actualCost" />--%>
                                    <logic:equal name="directMarginReportForm" value="customer" property="searchGroupBy">
                                        &nbsp;
                                    </logic:equal>
                                    <logic:equal name="directMarginReportForm" value="product" property="searchGroupBy">
                                        <nested:write property="actualCostFormatted" />
                                    </logic:equal>
                                    <logic:equal name="directMarginReportForm" value="costCode" property="searchGroupBy">
                                        <nested:write property="actualCostFormatted" />
                                    </logic:equal>
                                </td>
                                <td align="right" class="NArialL"><nested:write property="directMarginFormatted" /></td>
                            </tr>
                        </nested:iterate>
                        </TABLE>
                    </TD>
                </TR>
                <TR><TD colspan='4'><IMG src="<%=chipTracContext%>/jsp/includes/images/spacer.gif" height='20'></TD></TR>
            </TABLE>
            </html:form>
            <BR><BR><BR>
        </TD>
        <TD bgcolor="#ffffff"><IMG height=1 src="<%=chipTracContext%>/jsp/includes/images/spacer.gif" width=1></TD>
    </TR>
</TABLE>

<!-- Footer starts here -->
<%@ include file="/jsp/includes/footer.jsp" %>
<!-- footer end here -->

</BODY>
</HTML>